# management/initialization.py
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from algorithm.models import UserTagMastery, UserComprehensiveLevel, UserProblemRecommendation  # 替换为需要初始化的模型

from recommendation.models import SolvedProblem
from recommendation_pool.models import RecommendationStateMachine, UserRecommendationPool, RecommendationPoolQueue, \
    UserUndoPool
from recommendation_history.models import RecommendationHistory
from users.models import User


# @receiver(post_save, sender=User)
# def user_created_initialize(sender, instance, created, **kwargs):
#     if instance.luogu_uid:  # 检查 luogu_uid 是否有值
#         try:
#             initialize_user_data(instance)
#         except Exception as e:
#             # 记录错误信息，可以选择使用 logging
#             print(f"Error initializing user data for {instance.id}: {e}")


class DataInitializer:
    @classmethod
    def initialize_user_data(cls, user):
        # 该方法初始化数据完成后会创建备忘录
        user_id = user.id
        try:
            SolvedProblem.delete_user_all_problems(user.id)
            SolvedProblem.fetch_and_store_user_problems_by_id(user.id)

            UserTagMastery.initialize_user_tag_mastery(user_id=user_id)
            UserComprehensiveLevel.create_or_update_user_level(user_id=user_id)
            UserProblemRecommendation.initialize_user_problem_recommendation_scores(user_id=user_id)

            # StateMachine已废弃
            # RecommendationStateMachine.delete_state_machine(user_id=user_id)
            # RecommendationStateMachine.create_or_get_instance(user_id=user_id)

            UserRecommendationPool.delete_all_user_entries(user_id=user_id)
            UserRecommendationPool.init_user_recommendation_pool(user_id=user_id)

            RecommendationPoolQueue.delete_queue(user_id)
            RecommendationPoolQueue.create_or_get_queue(user_id)

            UserUndoPool.delete_all_for_user(user_id)
            # 串行的数据处理完毕后，立刻创建memento,并将创建memento的方法置为异步执行
            # 延迟导入
            from management.tasks import UserDataTasks

            UserDataTasks.submit_or_replace_task(user.id, UserDataTasks.async_create_memento)

        except ObjectDoesNotExist as e:
            # 处理特定的对象不存在异常
            print(f"User-related object does not exist for user {user_id}: {e}")
        except Exception as e:
            # 捕获其他可能的异常
            print(f"Error during user data initialization for user {user_id}: {e}")
